<?php

namespace App\Services;


use App\Models\CourseSectionQuestionAnswer;
use App\Models\CourseSectionQuestionAnswerBack;

class CourseSectionQuestionAnswerService extends BaseService
{
    /**
     * 获取列表
     * @return
     */
    public function list($sort,$order, $body, $course_id, $course_section_id, $users_id) {

        $latestPosts = CourseSectionQuestionAnswerBack::query('course_section_question_answer_backs')
            ->select('answers_id', 'from_users_id', 'to_users_id', 'body', 'praise','adopt')
            ->orderBy('adopt', 'desc')
            ->orderBy('created_at', 'desc')
            ->limit(1);
        $query = CourseSectionQuestionAnswer::leftJoin('users', 'users.id', '=', 'course_section_question_answers.users_id')
            ->leftJoinSub ($latestPosts, 'backs', function ($join) {
                $join->on('course_section_question_answers.id', '=', 'backs.answers_id');

            })
            ->leftJoin('users as backsUsers', 'backsUsers.id', '=', 'backs.from_users_id')
            ->select('course_section_question_answers.*','users.name as users_name','users.pic as users_pic'
                ,'backs.body as backsBody'
                ,'backsUsers.name as backs_name');



        if(!empty($body)){
            $query->where('body','like',"%$body%");
        }
        if(!empty($course_id)){
            $query->where('course_id',$course_id);
        }
        if(!empty($course_section_id)){
            $query->where('course_section_id',$course_section_id);
        }
        if(!empty($users_id)){
            $query->where('users_id',$users_id);
        }
        return $query->orderBy($sort,$order)->get();
    }
}
